<?php
/**
 * 支付服务
 *
 * @date    2018-07-26 09:40:34
 * @version $Id$
 */

namespace App\Commons\Services\Payment;

use App\Jobs\PaymentAutoCloseJob;
use Illuminate\Support\Str;
use Pay;

abstract class PayAdapter
{
    protected $pay_type;
    protected $pay_service;

    // 支付方式，用于判断是否自动关闭过期订单
    private $pay_methods = [
        'mp','miniapp','wap','scan','pos','app','web','transfer'
    ];

    protected function convertPayParams(array $options)
    {
        return $options;
    }

    public function __construct($pay_type)
    {
        $this->pay_service = Pay::{$pay_type}();
    }
    // 扫码支付
    public function pay(string $method, string $out_trade_no, string $subject, float $total_amount, array $options = [])
    {
        $order = $this->convertPayParams(compact('out_trade_no', 'subject', 'total_amount') + $options);
        $pay_config = $this->pay_service->{$method}($order);

        return $pay_config;
    }
    /**
     * 验证回调参数
     * @return [type] [description]
     */
    public function verify()
    {
        return $this->pay_service->verify();
    }

    public function __call(string $method, array $arguments)
    {
        $is_pay_method = in_array($method, $this->pay_methods);
        if (method_exists($this->pay_service, $method) || $is_pay_method) {
            if (method_exists($this, $method)) {
                $result = $this->{$method}(...$arguments);
            } elseif ($is_pay_method) {
                $result = $this->pay($method, ...$arguments);
            } else {
                $result = $this->pay_service->{$method}(...$arguments);
            }

            return $result;
        } else {
            throw_e('未实现支付方法：'. $method);
        }
    }
}
